﻿using System;
using System.Collections.Generic;
using IntelligentStorWpfApp.Model;
using IntelligentStorWpfApp.Interface;
using IntelligentStorWpfApp.Services;
using System.Data;
using log4net;

namespace IntelligentStorWpfApp.Controller
{
    public class UserController
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(UserController));
        UserInterface userServices = new UserServices();
        OperationLogController opControl = new OperationLogController();
        public List<User> GetUser(User user)
        {
            List<User> listUsers = new List<User>();
            try
            {
                DataTable dt = userServices.GetUsers(user);
                listUsers = formatUsersToList(dt);
            }
            catch (Exception ex)
            {
                log.Error(ex.ToString());
            }
            if(listUsers.Count>0)
                opControl.AddLog(new OperationLog() { UserName=user.UserName,OperatTime=DateTime.Now,Actions="登录成功"});
            else
                opControl.AddLog(new OperationLog() { UserName = user.UserName, OperatTime = DateTime.Now, Actions = "登录失败" });


            return listUsers;
        }

        public bool AddUser(User user)
        {
            return userServices.AddUser(user);
        }

        private List<User> formatUsersToList(DataTable dt)
        {
            List<User> listUsers = new List<User>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                User u = new User();
                u.ID = Convert.ToInt32(dt.Rows[i]["ID"]);
                u.FaceId = dt.Rows[i]["FaceId"] as byte[];
                u.UserName = dt.Rows[i]["UserName"].ToString();
                u.UserPwd = dt.Rows[i]["UserPwd"].ToString();
                listUsers.Add(u);
            }
            return listUsers;
        }
        public List<User> getAllUsers()
        {
            List<User> listUsers = new List<User>();

            try
            {
                DataTable dt = userServices.GetAllUsers();
                listUsers = formatUsersToList(dt);
            }
            catch (Exception ex)
            {

                log.Error(ex.ToString());
            }
            return listUsers;
        }
        public bool UpdateUserFace(User user)
        {
            return userServices.UpdateUserFace(user);
        }
    }
}
